import pandas as pd
from datetime import datetime
import os
import re

path = r'D:\MissionList\Misssons'

class MissionList:
    def __init__(self, path=r'MissionList.csv', read_json=False, read_csv=False):
        if read_json:
            self.list = self.read_json()
        elif read_csv:
            self.list = self.read_csv(path)
        else:
            self.list = self.init_list()
        self.path = 'D:/MissionList/Misssons'

    def get_a_mission(self):
        mission = input('任务(0 to stop):')
        if mission == '0':
            return None
        urgency = self.get_num(0)
        importance = self.get_num(1)
        total = urgency + importance
        return {'mission': mission, 'importance': importance, 'urgency': urgency, 'total': total}
    
    def sort(self, df):
        df.sort_values(by=['total', 'importance'], ascending=[False, False], inplace=True)
        return df

    def read_json(self, path):
        pass

    def read_csv(self, path):
        try:
            df = pd.read_csv(path, encoding='utf-8')
            sorted_df = df.sort_values(by=['total', 'importance'], ascending=[False, False])
            return sorted_df
        except Exception as e:
            print(e)

    def save_csv(self):
        try:
            # 读取 mission_count
            with open(os.path.join(self.path, 'control.txt'),'r') as f:
                line = f.readline()
                match = re.search(r'mission_count = (\d+);', line)
                mission_count = int(match.group(1))
                
            # 更新 mission_count
            with open(os.path.join(self.path, 'control.txt'), 'w') as f:
                newline = f'mission_count = {str(mission_count + 1)};'
                f.write(newline)
                
            #创建文件夹
            path = os.path.join(self.path, f'MissionList{match.group(1)}')
            os.makedirs(path, exist_ok=True)
            current_time = datetime.now().strftime("%Y-%m-%d %H时%M分.csv")
            self.list.to_csv(os.path.join(path, current_time), encoding='utf-8', index = False)
            print(f'文件已保存至 {path}/{current_time}')
        except Exception as e:
            print(e)

    def get_num(self, flag):
        name = '重要性' if flag else '紧急性'
        while True:
            try:
                num = int(input(f'{name}(-5-5):'))
                if num not in range(-5, 6):
                    print('重新输入')
                    continue
                return num
            except Exception as e:
                print(e, '\n重新输入')
                continue

    def init_list(self):
        missions = []
        count = 1
        while True:
            print('任务', count)
            count += 1
            mission = self.get_a_mission()
            if not mission:
                break
            else:
                missions.append(mission)
        df = pd.DataFrame(missions)
        print('任务清单已创建')
        return self.sort(df)

    def show(self):
        print(f'{"任务".ljust(6)} | {"任务名称".ljust(25)} | {"重要性".ljust(8)} | {"紧急性".ljust(8)}')
        for index, mission in self.list.iterrows():
            print(f'{str(index+1).ljust(6)} | {mission["mission"].ljust(25)} | {str(mission["importance"]).ljust(8)} | {str(mission["urgency"]).ljust(8)}')
    # 问题: 打印始终无法对齐？？？    
    
    def finish_mission(self):
        try:
            self.show()
            index = int(input('所完成任务的编号'))
            if index not in self.list.index.tolist():
                raise ValueError('编号不存在')
            self.list.drop(index,inplace=True)
            print('任务', index, '已完成')
            self.save_csv()
            return True
        except Exception as e:
            print(e)
            return False

    def add_mission(self):
        try:
            mission = self.get_a_mission()
            self.list.loc[len(self.list)]= mission
            self.save_csv()
        except Exception as e:
            print(e)
def menu():
    print('1 创建新清单')
    print('2 读取已有清单')
    print('3 退出')
    while True:
        num = input('请输入(1-3)')
        if num in ['1', '2', '3']:
            break
            
    if num == '1':
        list = MissionList()
        list.save_csv()
        
    elif num == '2':
        pattern = r'\.csv$'
        while True:
            count = input('请输入要读取的清单的编号')
            # print('count',count)
            folder = os.path.join(path, f'MissionList{count}')
            # print('folder', folder)
            if os.path.exists(folder):
                break
            print('编号不存在')
        try:
            files = os.listdir(folder)
            for file in files:
                if re.search(pattern, file):
                    list = MissionList(path = os.path.join(folder, file), read_csv=True)
                    list.show()
                    print(f'清单{count}读取已完成')
                    break
        except Exception as e:
            print(e)
        if list:
            while True:
                print('1. 新增任务')
                print('2. 完成任务')
                print('3. 退出')
                num = input('请输入(1-3)')
                if num not in ['1', '2', '3']:
                    continue
                if num == '1':
                    list.add_mission()
                elif num == '2':
                    list.finish_mission()
                elif num == '3':
                    exit()

    elif num == '3':
        exit()

# 当前改进方向：
"""
    √1. 增加方法 add_mission()
    √2. 增加方法 get_a_mission()
        并应用到init_missionlist()与add_mission()
    3. 为menu()中选项2添加完成与新增mission途径
"""

if __name__ == '__main__':
    menu()